package com.lanou.lenanapp.fragment;

import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.lanou.lenanapp.R;
import com.lanou.lenanapp.adapter.ImageFragmentAdapter;
import com.lanou.lenanapp.db.DatabaseHelper;
import com.lanou.lenanapp.entity.greendao.ImageEntity;
import com.lanou.lenanapp.util.Utils;
import com.lanou.lenanapp.view.SwipeRefreshLoadingLayout;
import com.lanou.lenanapp.volley.VolleySingleton;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 15/10/21.
 */
public class ImageFragment extends Fragment implements SwipeRefreshLoadingLayout.OnRefreshListener, SwipeRefreshLoadingLayout.OnLoadListener {

    private RecyclerView imageRecyclerView;
    private ImageFragmentAdapter imageFragmentAdapter;
    private GridLayoutManager manager;
    private Context context;
    private DatabaseHelper helper;
    private Dialog dialog;
    //上拉加载 下拉刷新
    private SwipeRefreshLoadingLayout imageswipeRefreshLoadingLayout;

    VolleySingleton volleySingleton = VolleySingleton.getInstance();

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.activity_fragment_image, null);

        imageRecyclerView = (RecyclerView) v.findViewById(R.id.imageRecyclerView);
        imageswipeRefreshLoadingLayout = (SwipeRefreshLoadingLayout) v.findViewById(R.id.imageswipeRefreshLoadingLayout);
        imageswipeRefreshLoadingLayout.setOnRefreshListener(this);
        imageswipeRefreshLoadingLayout.setOnLoadListener(this);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        helper = DatabaseHelper.getHelper();
        manager = new GridLayoutManager(context, 1);
        imageFragmentAdapter = new ImageFragmentAdapter(getActivity());
        imageRecyclerView.setLayoutManager(manager);
        imageRecyclerView.setAdapter(imageFragmentAdapter);//绑定适配器

        //检查网络状态 决定什么方式显示
        List<ImageEntity> list = helper.queryAllImg();
        boolean lenan = checkNet(getActivity());
        if (lenan){
            initData();
        }else {
            if (list != null && list.size() > 0){
                imageFragmentAdapter.addData(list);
            }else {
                Toast.makeText(getActivity(), "请检查您的网络...", Toast.LENGTH_SHORT).show();
            }
        }

    }

    /***
     * 判断是否有网络  返回的是boolean类型的
     * **/
    public static boolean checkNet(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                Log.i("TAG", "info =" + info);
                if (info != null && info.isConnected()) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            Log.e("TAG", "exception=" + e.toString());
            return false;
        }
        return false;
    }



    //下拉刷新
    @Override
    public void onRefresh() {
        initData();
    }

    private String time;
    private int t;
    private void initData() {
        dialog = Utils.createloadingDialog(getActivity(), "玩命加载中...");
        dialog.show();
        String url = "http://120.55.151.67/weibofun/weibo_list.php?apiver=10701&category=weibo_pics&page=0&page_size=30&max_timestamp=-1&latest_viewed_ts=1445949900&platform=iphone&appver=1.9&buildver=1.9.4&udid=0FD678F7-07AA-4EBF-BB39-EB79EAB40753&sysver=7.0.4";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                dialog.dismiss();
                imageswipeRefreshLoadingLayout.setRefreshing(false);
                if (response != null && response.has("items")){
                    try {
                        JSONArray img = response.getJSONArray("items");
                        List<ImageEntity> items = new ArrayList<ImageEntity>();
                        Gson gson = new Gson();
                        for (int i = 0; i < img.length(); i++){
                            String str = img.getString(i);
                            ImageEntity im = gson.fromJson(str, ImageEntity.class);
                            items.add(im);

                        }
                        helper.saveImageList(items);
                        imageFragmentAdapter.addData(items);
                        time = items.get(15).getUpdate_time();
                        t = Integer.parseInt(time);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }finally {

                    }

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        //将本次请求加入请求队列
        volleySingleton.addRequest(request);
    }


    //上拉加载
    @Override
    public void onLoad() {
        LoadContent();
    }

    int page = 0;
    int tamptimes = 0;
    private void LoadContent() {
        page++;
        t = t - tamptimes;
        tamptimes = tamptimes + 13500;
        String url = "http://120.55.151.67/weibofun/weibo_list.php?apiver=10701&category=weibo_pics&page="+ page
                +"&page_size=15&max_timestamp="+ t +
                "&latest_viewed_ts=-1&platform=iphone&appver=1.9&buildver=1.9.4&udid=0FD678F7-07AA-4EBF-BB39-EB79EAB40753&sysver=7.0.4";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                imageswipeRefreshLoadingLayout.setLoading(false);
                if (response != null && response.has("items")){
                    try {
                        JSONArray img = response.getJSONArray("items");
                        List<ImageEntity> items = new ArrayList<ImageEntity>();
                        Gson gson = new Gson();
                        for (int i = 0; i < img.length(); i++){
                            String str = img.getString(i);
                            ImageEntity im = gson.fromJson(str, ImageEntity.class);
                            items.add(im);
                        }
                        imageFragmentAdapter.loadData(items);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }finally {

                    }

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        //将本次请求加入请求队列
        volleySingleton.addRequest(request);

    }
}
